/**
 * File ManufacturerControlAgentCB.java created by Pablo Díaz Fernández
 * on 06/04/2012 for the project supply-chain-simulator
 */
package org.lsk.pfc.scsim.model.behaviour;

import java.math.BigDecimal;

import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

import org.apache.log4j.Logger;
import org.lsk.pfc.scsim.model.agent.ControlAgent;
import org.lsk.pfc.scsim.model.messages.InformationAgentMessageFactory;
import org.lsk.pfc.scsim.model.messages.MessageFactory;
import org.lsk.pfc.scsim.model.messages.NegotiationMessageFactory;

/**
 * Cyclic behaviour executed for the control agent of the manufacturer
 * multi-agent system of the supply chain.
 * 
 * @author Pablo Díaz Fernández
 * 
 */
public final class ManufacturerControlAgentCB extends ControlAgentCB {

	/**
	 * Serial version ID.
	 */
	private static final long serialVersionUID = 8502130927825606067L;

	/**
	 * Creates the logger for the class.
	 * 
	 * @see org.lsk.pfc.scsim.model.behaviour.ControlAgentCB#createLogger()
	 */
	@Override
	protected void createLogger() {
		super.setLogger(Logger.getLogger(this.getClass()));
	}

	/**
	 * Performs the main operations of this behaviour. Checks for stocks and
	 * requests and decides if should manufacture more products.
	 * 
	 * @param tick
	 *            current time tick.
	 * @see org.lsk.pfc.scsim.model.behaviour.ControlAgentCB#process(long)
	 */
	@Override
	protected void process(final long tick) {
		ControlAgent agent = (ControlAgent) this.myAgent;

		// Waits for other MAS requests
		ACLMessage inMsg = null;
		do {
			inMsg = agent
			        .receive(NegotiationMessageFactory.NEG_REQ_MSG_TEMPLATE);
		} while (inMsg == null);

		int amountRequested = Integer.valueOf(inMsg
		        .getUserDefinedParameter(NegotiationMessageFactory.AMOUNT));

		// Checks for stocks
		ACLMessage outIAMsg = MessageFactory.getInformationAgentMF()
		        .queryMessage(agent.getInformationAgentAID(), agent.getAID(),
		                tick, InformationAgentMessageFactory.STOCKS_MESSAGE);
		agent.send(outIAMsg);

		// Waits for stock details
		ACLMessage inIAMsg = null;
		inIAMsg = agent.blockingReceive(
				InformationAgentMessageFactory.RESPONSE_MSG_TEMPLATE);

		int amountAvailable = Integer.valueOf(inIAMsg.getContent());
		BigDecimal price = new BigDecimal(0);

		// Response price & amount
		// Send response to other MAS
		ACLMessage outMsg = MessageFactory.getNegotiationMF()
		        .getResponseRequestProductMSG(inMsg, amountAvailable, price);
		agent.send(outMsg);

		// Waits for confirmation/cancelation from the other MAS.
		inMsg = agent.blockingReceive(
				NegotiationMessageFactory.NEG_PUR_MSG_TEMPLATE);
		
		if (inMsg.getPerformative() == ACLMessage.AGREE) {
	        // Confirmed purchase
			// Ask information agent to update stocks
			// Ask information agent to update requests.
			
        }

	}

}
